<!DOCTYPE html>
<script src="../../resources/js-test.js"></script>

<div id="sandbox"></div>

<script>
    description("Media query listeners should fire grouped by the MediaQueryList.");
    var jsTestIsAsync = true;

    var sandbox = document.getElementById("sandbox");
    var iframe = document.createElement("iframe");
    sandbox.appendChild(iframe);

    var matchMedia = iframe.contentWindow.matchMedia;
    var mediaList1 = matchMedia("(max-width: 100px)");
    var mediaList2 = matchMedia("(max-width: 100px)");
    var mediaList3 = matchMedia("(max-width: 100px)");

    var listenersCalled = [];

    function makeListener(label) {
        return function() { listenersCalled.push(label); };
    }

    mediaList3.addListener(makeListener("mediaList3_1"));
    mediaList2.addListener(makeListener("mediaList2_1"));
    mediaList1.addListener(makeListener("mediaList1_1"));
    mediaList2.addListener(makeListener("mediaList2_2"));
    mediaList3.addListener(verifyResult);

    requestAnimationFrame(() => {
        iframe.style.width = "80px";
    });

    var expectedResult = ["mediaList1_1", "mediaList2_1", "mediaList2_2", "mediaList3_1"];
    function verifyResult() {
        shouldBe("listenersCalled", "expectedResult");
        finishJSTest();
    }
</script>
